package apptoko.com.download;

import java.io.File;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import apptoko.com.AllDownloadingActivity;
import apptoko.com.AppStoreVnApplication;
import apptoko.com.SettingsActivity;
import apptoko.com.ShowCompleteDownloadData;
import apptoko.com.VideoActivity;
import apptoko.com.adapter.NotificationHelper;
import apptoko.com.event.Event;
import apptoko.com.network.InstallBackgroundTask;
import apptoko.com.util.Utils;

import apptoko.com.R;

import de.greenrobot.event.EventBus;

public class DownloadReceiver extends BroadcastReceiver {
	SystemFacade mSystemFacade = null;

    public void onReceive(Context context, Intent intent) {
        if (mSystemFacade == null) {
            mSystemFacade = new RealSystemFacade(context);
        }
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
            startService(context);
        } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            @SuppressWarnings("deprecation")
			NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (info != null && info.isConnected()) {
                startService(context);
            }
        } else if (action.equals(Constants.ACTION_RETRY)) {
            startService(context);
        } else if (action.equals(Constants.ACTION_OPEN) || action.equals(Constants.ACTION_LIST) || action.equals(Constants.ACTION_HIDE)) {
            handleNotificationBroadcast(context, intent);
        } else if(action.equalsIgnoreCase(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
        	String filename = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_ID);
        	String title = intent.getStringExtra(DownloadManager.EXTRA_DOWNLOAD_TITLE);
        	if(filename != null && filename.endsWith("apk")){
        		EventBus.getDefault().post(new Event.DownloadSuccessEvent(1, title, "android"));
        		boolean autoInstall = false;
                try {
                 autoInstall = context.getSharedPreferences(apptoko.com.util.Constants.SHARED_NAME, Activity.MODE_PRIVATE).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
		          } catch (Exception e) {
		           // TODO: handle exception\
		           context.getSharedPreferences(apptoko.com.util.Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putBoolean(SettingsActivity.KEY_AUTO_INSTALL,
		             false)
		           .commit();
		          }
        		if(!autoInstall){
        			Utils.installAPK(context, filename);
        		} else {
        			InstallBackgroundTask task = new InstallBackgroundTask(context);
        			task.execute(filename, title);
        		}
        	} else {
        		Intent notifyIntent = null;
        		if(filename.endsWith("epub")){
        			EventBus.getDefault().post(new Event.DownloadSuccessEvent(1, title, "ebook"));
        			notifyIntent = new Intent(Intent.ACTION_VIEW);
        			notifyIntent.setDataAndType(Uri.parse(filename), "application/epub+zip");
        			notifyIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        			notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		} else if(filename.endsWith("mp4")){
        			EventBus.getDefault().post(new Event.DownloadSuccessEvent(1, title, "movie"));
        			notifyIntent = new Intent(context, VideoActivity.class);
        			notifyIntent.putExtra(apptoko.com.util.Constants.MOVIE_URL, Uri.parse(filename).toString());
        			notifyIntent.putExtra(apptoko.com.util.Constants.MOVIE_TITLE, title);
        			notifyIntent.putExtra(apptoko.com.util.Constants.MOVIE_EPISODE, "");
        			notifyIntent.putExtra(apptoko.com.util.Constants.KEY_PRICE_1, 0);
        			notifyIntent.putExtra(apptoko.com.util.Constants.KEY_PRICE_2, 0);
        			notifyIntent.putExtra(apptoko.com.util.Constants.KEY_VERSION, 0);
        			notifyIntent.putExtra(apptoko.com.util.Constants.KEY_SLUG, "");
        			notifyIntent.putExtra(apptoko.com.util.Constants.IS_MOVIE_PURCHASED, true);
        			notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		} else {
        			EventBus.getDefault().post(new Event.DownloadSuccessEvent(1, title, "comic"));
        			notifyIntent = new Intent(Intent.ACTION_VIEW);
        			notifyIntent.setDataAndType(Uri.parse(filename), "application/x-acv");
        			notifyIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        			notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		}
        		NotificationHelper notification = new NotificationHelper(context);
    		    PendingIntent pending = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        		notification.complete(title.length(), null, context.getResources().getString(R.string.download_complete), title, title, pending);
        		Intent startActivity=new Intent(context, ShowCompleteDownloadData.class);
        		if(filename.endsWith("obb")){
        			String _filename=Utils.getFileName(filename);
        			String packageName=AppStoreVnApplication.getdownloadPackageName(_filename);
        			if(packageName!=null){
        				boolean isInstallTheApk=Utils.isPackageExisted(context, packageName);
                        startActivity.putExtra("isInstalled", isInstallTheApk);
                        startActivity.putExtra("package", packageName);
        			}else{
        				startActivity.putExtra("isInstalled", false);
                        startActivity.putExtra("package", "");
        			}
        			startActivity.putExtra("appinfo", title+" "+context.getResources().getString(R.string.notification_download_complete));
                    startActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(startActivity);
        		}
        	}
        } else if(action.equalsIgnoreCase(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
        	Intent notifyIntent = new Intent(context, AllDownloadingActivity.class);
    		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		context.startActivity(notifyIntent);
        }
    }

    /**
     * Handle any broadcast related to a system notification.
     */
    private void handleNotificationBroadcast(Context context, Intent intent) {
        Uri uri = intent.getData();
        String action = intent.getAction();
        if (Constants.LOGVV) {
            if (action.equals(Constants.ACTION_OPEN)) {
                Log.v(Constants.TAG, "Receiver open for " + uri);
            } else if (action.equals(Constants.ACTION_LIST)) {
                Log.v(Constants.TAG, "Receiver list for " + uri);
            } else { // ACTION_HIDE
                Log.v(Constants.TAG, "Receiver hide for " + uri);
            }
        }

        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        if (cursor == null) {
            return;
        }
        try {
            if (!cursor.moveToFirst()) {
                return;
            }

            if (action.equals(Constants.ACTION_OPEN)) {
                openDownload(context, cursor);
                hideNotification(context, uri, cursor);
            } else if (action.equals(Constants.ACTION_LIST)) {
                sendNotificationClickedIntent(intent, cursor);
            } else { // ACTION_HIDE
                hideNotification(context, uri, cursor);
            }
        } finally {
            cursor.close();
        }
    }

    /**
     * Hide a system notification for a download.
     * @param uri URI to update the download
     * @param cursor Cursor for reading the download's fields
     */
    private void hideNotification(Context context, Uri uri, Cursor cursor) {
        mSystemFacade.cancelNotification(ContentUris.parseId(uri));

        int statusColumn = cursor.getColumnIndexOrThrow(Downloads.COLUMN_STATUS);
        int status = cursor.getInt(statusColumn);
        int visibilityColumn =
                cursor.getColumnIndexOrThrow(Downloads.COLUMN_VISIBILITY);
        int visibility = cursor.getInt(visibilityColumn);
        if (Downloads.isStatusCompleted(status)
                && visibility == Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) {
            ContentValues values = new ContentValues();
            values.put(Downloads.COLUMN_VISIBILITY,
                    Downloads.VISIBILITY_VISIBLE);
            context.getContentResolver().update(uri, values, null, null);
        }
    }

    /**
     * Open the download that cursor is currently pointing to, since it's completed notification
     * has been clicked.
     */
    private void openDownload(Context context, Cursor cursor) {
        String filename = cursor.getString(cursor.getColumnIndexOrThrow(Downloads._DATA));
        String mimetype = cursor.getString(cursor.getColumnIndexOrThrow(Downloads.COLUMN_MIME_TYPE));
        Uri path = Uri.parse(filename);
        // If there is no scheme, then it must be a file
        if (path.getScheme() == null) {
            path = Uri.fromFile(new File(filename));
        }

        Intent activityIntent = new Intent(Intent.ACTION_VIEW);
        activityIntent.setDataAndType(path, mimetype);
        activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(activityIntent);
        } catch (ActivityNotFoundException ex) {
            Log.d(Constants.TAG, "no activity for " + mimetype, ex);
        }
    }

    /**
     * Notify the owner of a running download that its notification was clicked.
     * @param intent the broadcast intent sent by the notification manager
     * @param cursor Cursor for reading the download's fields
     */
    private void sendNotificationClickedIntent(Intent intent, Cursor cursor) {
        String pckg = cursor.getString(cursor.getColumnIndexOrThrow(Downloads.COLUMN_NOTIFICATION_PACKAGE));
        if (pckg == null) {
            return;
        }

        String clazz = cursor.getString(cursor.getColumnIndexOrThrow(Downloads.COLUMN_NOTIFICATION_CLASS));
        boolean isPublicApi = cursor.getInt(cursor.getColumnIndex(Downloads.COLUMN_IS_PUBLIC_API)) != 0;

        Intent appIntent = null;
        if (isPublicApi) {
            appIntent = new Intent(DownloadManager.ACTION_NOTIFICATION_CLICKED);
            appIntent.setPackage(pckg);
        } else { // legacy behavior
            if (clazz == null) {
                return;
            }
            appIntent = new Intent(Downloads.ACTION_NOTIFICATION_CLICKED);
            appIntent.setClassName(pckg, clazz);
            if (intent.getBooleanExtra("multiple", true)) {
                appIntent.setData(Downloads.CONTENT_URI);
            } else {
                long downloadId = cursor.getLong(cursor.getColumnIndexOrThrow(Downloads._ID));
                appIntent.setData(ContentUris.withAppendedId(Downloads.CONTENT_URI, downloadId));
            }
        }
        mSystemFacade.sendBroadcast(appIntent);
    }

    private void startService(Context context) {
        context.startService(new Intent(context, DownloadService.class));
    }
}
